from flask import Blueprint, jsonify, make_response
from flask_restful import Api,Resource,reqparse
from models.user import OAuthUserModel,User
from common.utils.my_output_json import custom_uotput_json
oatuh_user_bp = Blueprint('oatuh_user_bp',__name__,url_prefix='/oauth')
from flask import current_app
api = Api(oatuh_user_bp)
import time,hmac,base64,urllib,requests,json
from common.jwt_token import gen_toen
from urllib.parse import parse_qs,urlencode
@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = custom_uotput_json(data, code)
    return resp
class DingDingResource(Resource):

    def get_dingding_user(self,code):
        # 2 . 构造三个参数的值
        appid = current_app.config.get('APPID')
        appSecret = current_app.config.get('APPSECRET')
        timestamp = str(int(time.time() * 1000))
        signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),
                                              timestamp.encode('utf-8'), digestmod='sha256').digest())
        base_url = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='
        # 拼接url
        url = base_url + urllib.parse.quote(signature.decode('utf-8')) + "&timestamp="+timestamp + "&accessKey=" + appid

        data = json.dumps({'tmp_auth_code':code})
        try:
            resp = requests.post(url,data,headers={'Content-Type':'application/json'})
            user_info = resp.json()
            print("user...",user_info)
        except Exception as e:
            return {'code':500,'message':'post请求获取用户信息失败'}

        if user_info['errcode'] != 0:
            return {'code': 500, 'message': '获取用户信息失败'}
        user_info_dict = user_info['user_info']
        print("user_info",user_info_dict)
        return user_info_dict

    def get(self):
        """
        1.获取code值
        2.构建accessKey(应用的AppKey)
            timestamp (当前的时间戳，单位是毫秒)
            signature:(appSecret计算出来的签名值)
            三个参数的值
        3.发请求：
        post:https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=ACCESS_KEY&timestamp=TIMESTAMP&signature=SIGNATURE
        :return: userInfo
        """
        parser = reqparse.RequestParser()
        parser.add_argument('code')
        args = parser.parse_args()
        # 1 . 获取code值
        code = args.get('code')
        user_info = self.get_dingding_user(code)
        #根据用户的信息获取钉钉的openid
        openid = user_info['openid']
        oauth_user = OAuthUserModel.query.filter_by(oauth_id=openid,oauth_type='dingding').first()
        # True 说明绑定过
        if oauth_user:
            # 获取绑定的用户信息
            user = User.query.filter_by(uid=oauth_user.user).first()
            print(".....",user)
            data = {
                'uid':user.uid,
                'account':user.account
            }
            token = gen_toen(data)
            return {'code':200,'account':user.account,'uid':user.uid,'token':token}
        else:
            # Flase 说明没绑定用户  去绑定用户
            return {'message':'请绑定用户','uid':openid}
api.add_resource(DingDingResource,'/dingding')

from werkzeug.security import check_password_hash
from models import db
class DingdingBindUser(Resource):
    """
    1.获取用户信息：用户名，密码，uid
    2.判断用户是否存在数据库里
        1.存在
            校验密码
            直接绑定
        2.不存在
            先去注册
    """
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('account')
        parser.add_argument('password')
        parser.add_argument('unid')
        args = parser.parse_args()
        account = args.get('account')
        pwd = args.get('password')
        unid = args.get('unid')
        #判断用户是否在数据库存在
        user = User.query.filter_by(account=account).first()

        if not user:
            #用户不存在
            return {'message':'用户未注册请先注册','code':400}
        else:
            rest = check_password_hash(user.password,pwd)
            if not rest:
                #密码错误
                return {'message':'密码错误','code':400}
            else:
                #绑定用户
                user_ = OAuthUserModel(oauth_id=unid,user=user.uid,oauth_type='dingding')
                db.session.add(user_)
                db.session.commit()
                data = {
                    'uid':user.uid,
                    'account':user.account
                }
                token = gen_toen(data)
                data_ = {
                    'account':user.account,
                    'token':token,
                    'uid':user.uid
                }
                return {'message':'绑定成功','code':200,'data':data_}

api.add_resource(DingdingBindUser,'/dingding/bind')





